package com.sfac.javaSpringBoot.config;

import com.sfac.javaSpringBoot.interceptor.ViewMappingInterceptor;
import org.apache.catalina.connector.Connector;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.servlet.server.ServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.ResourceUtils;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * @Description WebMvcConfig
 * @Author HymanHu
 * @Date 2021/8/18 15:17
 */
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
    @Value("${server.http.port}")
    private int httpPort;
    @Autowired
    private ResourcesConfigerBean resourcesConfigerBean;
    @Autowired
    private ViewMappingInterceptor viewMappingInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(viewMappingInterceptor).addPathPatterns("/**");
    }
    //注册
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        String systemName = System.getProperty("os.name");
        if (systemName.toLowerCase().startsWith("win")){
            registry.addResourceHandler(resourcesConfigerBean.getPathPattern())
           .addResourceLocations(ResourceUtils.FILE_URL_PREFIX
                   +resourcesConfigerBean.getWindowsLocation());

        }else {
            registry.addResourceHandler( resourcesConfigerBean.getLinuxLocation())
                    .addResourceLocations(ResourceUtils.FILE_URL_PREFIX+
                            resourcesConfigerBean.getLinuxLocation());
        }

        //将本地的绝对路径映射成系统的相对路径
//        registry.addResourceHandler("/upload/**")
                //记得加斜杠
//                .addResourceLocations(ResourceUtils.FILE_URL_PREFIX+"E:/upload/");
    }
    @Bean
    public Connector connector() {
        Connector connector = new Connector();
        connector.setPort(httpPort);
        connector.setScheme("http");
        return connector;
    }

    @Bean
    public ServletWebServerFactory servletWebServerFactory() {
        TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory();
        factory.addAdditionalTomcatConnectors(connector());
        return factory;
    }
}
